<template>
  <div id="commodity-create" class="Row_content" style="width:560px;">
    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="110">
      <FormItem label="分类名称：" prop="classifyName" :maxlength='20'>
        <Input v-model="formValidate.classifyName" placeholder="请输入" class='input-wid' :maxlength='20' @on-keyup='filterName' @on-blur="filterName"></Input>
      </FormItem>
      <FormItem label="上级分类：" prop="preClassify">
        <Row type='flex' style="width:430px;">
          <Col>
            <Select v-model="formValidate.preClassify" class='input-wid' disabled>
              <Option v-for="(item, index) in preClassifyList" :value="item.categoryId" :key="index">{{item.categoryName}}</Option>
            </Select>
          </Col>
          <Col style='margin-left:10px;color: #808695;'><span>不选择分类默认为顶级分类</span></Col>
        </Row>
      </FormItem>
      <FormItem label="属性名称：" prop="attributeName" v-if='formValidate.preClassify'>
        <Select v-model="formValidate.attributeName" class='input-wid'>
          <Option v-for="(item, index) in attributeNameList" :value="item.packageId" :key="index">{{item.packageName}}</Option>
        </Select>
      </FormItem>
      <FormItem label="排序：" prop="order">
        <Input v-model="formValidate.order" placeholder="请输入" class='input-wid' :maxlength='3' @on-keyup='keyUp' @on-blur="keyUp"></Input>
      </FormItem>
      <FormItem label="关键词：" prop="keyword">
        <Row type='flex' style="width:430px;">
          <Col>
            <Input v-model="formValidate.keyword" placeholder="请输入" class='input-wid' :maxlength='100'></Input>
          </Col>
          <Col style='margin-left:10px;color: #808695;'><span>关键词用空格分割</span></Col>
        </Row>
      </FormItem>
      <FormItem label="是否显示：" prop="isShow">
        <RadioGroup v-model="formValidate.isShow" size="large">
          <Radio label="1">显示</Radio>
          <Radio label="0" style="margin-left:50px">隐藏</Radio>
        </RadioGroup>
      </FormItem>
      <FormItem label="分类描述：">
        <div>
          <Input v-model="formValidate.remark"
          type="textarea" style="width:320px" :maxlength='200'
          :autosize="{ minRows: 5, maxRows: 8 }"
          placeholder="请输入内容"></Input>
          <span class="rol_tipsd" style="width: 320px">{{desCount}}/200</span>
        </div>
      </FormItem>
      <FormItem>
        <Button type="primary" class="btn" @click="handleSubmit">确定</Button>
        <Button class="btn" style="margin-left: 24px" @click="handleReset">取消</Button>
      </FormItem>
    </Form>
  </div>
</template>

<script>
import { routeEqual } from '@/libs/util'
import { detailClassify, getClassifyList, editClassify, getAttributeList } from '@/api/commondity/index'
export default {
  name: 'classify_edit',
  computed: {
    desCount () {
      if (this.formValidate.remark) {
        return this.formValidate.remark.length
      } else {
        return 0
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (vm.categoryId !== to.params.id) {
        vm.categoryId = to.params.id
        vm.type = to.query.type
        vm.getDetail()
      }
    })
  },
  data () {
    return {
      type: '',
      categoryId: '',
      submitLock: false,
      attributeNameList: [],
      preClassifyList: [],
      formValidate: {
        classifyName: '',
        attributeName: '',
        preClassify: '',
        order: '',
        keyword: '',
        remark: '',
        isShow: ''
      },
      ruleValidate: {
        classifyName: { required: true, message: '请输入分类名称', trigger: 'blur' },
        // order: { required: true, message: '请输入排序号', trigger: 'blur' },
        // keyword: { required: true, message: '请输入关键词', trigger: 'blur' },
        isShow: { required: true, message: '请选择是否显示', trigger: 'change' }
      }
    }
  },
  methods: {
    keyUp () {
      this.formValidate.order = this.formValidate.order.replace(/[^\d]/g, '').replace(/^0{1,}/g, '')
    },
    filterName () {
      this.formValidate.classifyName = this.formValidate.classifyName.replace(/[^\u4e00-\u9fa5]/g, '')
    },
    handleSubmit () {
      this.$refs.formValidate.validate(valid => {
        if (valid) {
          let data = {
            merchantId: this.$store.state.user.merchantId,
            seq: this.formValidate.order,
            categoryName: this.formValidate.classifyName,
            categoryType: '0',
            categoryDesc: this.formValidate.remark,
            updater: this.$store.state.user.userId,
            updaterName: this.$store.state.user.userName,
            keyword: this.formValidate.keyword,
            display: this.formValidate.isShow,
            categoryId: this.$route.params.id
          }
          if (this.formValidate.preClassify) {
            data.parentId = this.formValidate.preClassify
            data.packageId = this.formValidate.attributeName
          }
          if (this.submitLock) {
            return
          }
          this.submitLock = true
          editClassify(data).then(res => {
            this.submitLock = false
            if (res.data.status === 200) {
              this.$Message.success('编辑成功!')
              this.handleReset()
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          }).catch(err => {
            this.submitLock = false
            this.$Message.error(`${err}`)
          })
        }
      })
    },
    handleReset () {
      this.$store.commit('closeTag', this.$route)
      this.$store.commit('setTagNavList', this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item)))
      if (this.type === '1') {
        this.$nextTick(() => {
          this.$router.push({
            name: 'commodity_classify_list'
          })
        })
      } else if (this.type === '2') {
        this.$nextTick(() => {
          this.$router.push({
            name: 'commodity_lower_list',
            params: {
              id: this.formValidate.preClassify
            }
          })
        })
      }
    },
    getDetail () {
      detailClassify({
        merchantId: this.$store.state.user.merchantId,
        categoryId: this.categoryId,
        categoryType: '0'
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.formValidate.classifyName = result.data.categoryName ? result.data.categoryName : ''
          this.formValidate.order = result.data.seq ? result.data.seq + '' : ''
          this.formValidate.keyword = result.data.keyword
          this.formValidate.remark = result.data.categoryDesc
          this.formValidate.isShow = result.data.isShow + ''
          if (this.formValidate.classifyName) {
            this.formValidate.attributeName = result.data.packageId ? result.data.packageId : ''
          }
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    // 获取属性列表
    getList () {
      getAttributeList({
        merchantId: this.$store.state.user.merchantId,
        isShow: '1'
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.attributeNameList = result.data || []
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    // 获取上级分类
    getData () {
      getClassifyList({
        merchantId: this.$store.state.user.merchantId,
        level: '1'
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.preClassifyList = result.data.categories || []
          this.getList()
          this.getDetail()
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    }
  },
  created () {
    this.type = this.$route.query.type
    if (this.$route.query.categoryId) {
      this.formValidate.preClassify = this.$route.query.categoryId
    }
    this.categoryId = this.$route.params.id
    this.getData()
  }
}
</script>

<style scoped>
.input-wid{ width: 260px;}
.btn{ width: 100px;}
</style>
